package ti.me.seek2chat.adapters

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Base64
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import ti.me.seek2chat.databinding.ItemContainerRecentConversionBinding
import ti.me.seek2chat.listeners.ConversionListener
import ti.me.seek2chat.models.ChatMessage
import ti.me.seek2chat.models.User

/**
 * RecentConversationsAdapter 是一个 RecyclerView 适配器，用于显示最近的会话列表。
 *
 * @param chatMessages 聊天消息列表
 * @param conversionListener 会话点击监听器
 */
class RecentConversationsAdapter(
    private var chatMessages: ArrayList<ChatMessage>,
    private val conversionListener: ConversionListener
) : RecyclerView.Adapter<RecentConversationsAdapter.ConversationViewHolder>() {
    /**
     * ConversationViewHolder 是一个 ViewHolder，用于绑定会话数据到视图。
     *
     * @param binding 视图绑定对象
     */
    class ConversationViewHolder(private val binding: ItemContainerRecentConversionBinding) :
        RecyclerView.ViewHolder(binding.root) {
        /**
         * 绑定会话数据到视图。
         *
         * @param chatMessage 聊天消息对象
         * @param conversionListener 会话点击监听器
         */
        fun setData(chatMessage: ChatMessage, conversionListener: ConversionListener) {
            binding.imageProfile.setImageBitmap(getConversionImage(chatMessage.conversionImage))
            binding.textName.text = chatMessage.conversionName
            binding.textRecentMessage.text = chatMessage.message
            binding.root.setOnClickListener {
                val user = User(
                    id = chatMessage.conversionId,
                    name = chatMessage.conversionName,
                    image = chatMessage.conversionImage,
                    token = "",
                    email = ""
                )
                conversionListener.onConversionClicked(user)
            }
        }

        /**
         * 将 Base64 编码的字符串转换为 Bitmap。
         *
         * @param encodedImage Base64 编码的字符串
         * @return 解码后的 Bitmap
         */
        private fun getConversionImage(encodedImage: String): Bitmap {
            val bytes = Base64.decode(encodedImage, Base64.DEFAULT)
            return BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
        }
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ConversationViewHolder {
        return ConversationViewHolder(
            ItemContainerRecentConversionBinding.inflate(
                LayoutInflater.from(
                    parent.context
                ), parent, false
            )
        )
    }

    override fun getItemCount(): Int {
        return chatMessages.size
    }

    override fun onBindViewHolder(holder: ConversationViewHolder, position: Int) {
        holder.setData(chatMessages[position], conversionListener)
    }
}